package com.software.car.controller;

import com.software.car.api.UserService;
import com.software.car.common.enums.ResultEnum;
import com.software.car.common.enums.RoleEnum;
import com.software.car.common.utils.CommonResult;
import com.software.car.entity.dto.UserInsertDto;
import com.software.car.entity.dto.WeChatLoginDto;
import com.software.car.entity.vo.UserDetailVo;
import com.software.car.common.utils.JwtUtil;
import com.software.car.entity.dto.WebLoginDto;
import com.software.car.service.FeaturesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 *
 * 登录模块
 *
 * @Description
 * @Author 魔法はまだ解けない
 * @Date 2021/1/21
 */
@RestController
@RequestMapping("/public")
public class LoginController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    UserService userService;
    @Autowired
    FeaturesService featuresService;

    /**
     * 公共
     * 微信登陆
     * @param weChatLoginDtoa
     * @return 返回token
     */
    @PostMapping("/login/wx")
    public CommonResult wxLogin(@RequestBody WeChatLoginDto weChatLoginDtoa) {
        UserDetailVo user = userService.getUser(weChatLoginDtoa);
        HashMap<String, Object> hashMap = loginRes(user);
        return CommonResult.success(hashMap);
    }
    /**
     * 公共
     * Web登陆
     * @param webLoginDto
     * @return
     */
    @PostMapping("/login/web")
    public CommonResult WebLogin(@RequestBody WebLoginDto webLoginDto){
        UserDetailVo user = userService.getUser(webLoginDto);
        HashMap<String, Object> hashMap = loginRes(user);
        return CommonResult.success(hashMap);
    }

    /**
     *
     * 用户注册
     * @param userInsertDto
     * @return
     */
    @PostMapping("/singUp")
    public CommonResult singUp(@RequestBody UserInsertDto userInsertDto) {
        //生成角色
        Integer role = featuresService.getRole(userInsertDto.getSecretKey());
        userInsertDto.setRole(role);
        //检验账号是否存在
        UserDetailVo userByAccount = userService.getUserByAccount(userInsertDto.getAccount());
        if (userByAccount != null) {
            return CommonResult.fail(ResultEnum.ACCOUNT_HAS_EXIT);
        }
        int i = userService.insertUser(userInsertDto);
        if (i == 0) {
            return CommonResult.fail(ResultEnum.INSERT_USER_FAIL);
        }
        return CommonResult.success();
    }


    /**
     * 方法：
     * 封装用户登陆信息
     * 并打印日志
     * @param user
     * @return
     */
    private HashMap<String, Object> loginRes(UserDetailVo user){
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", JwtUtil.generate(user.getId()));
        hashMap.put("user",user);
        logger.info("用户："+user.getName()+" || id："+user.getId()+" ||登录成功");
        return hashMap;
    }
}
